"use client";

import { useEffect, useState, useCallback, useRef } from 'react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Heart, MessageCircle, Loader2, Image as ImageIcon, Send } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogClose } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { useAuth } from '@/context/authContext';
import { toast } from 'sonner';
import { get, post, del } from '@/lib/request';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';

interface MomentAuthor {
  id: string;
  username: string;
  avatar: string | null;
}

interface Comment {
  id: string;
  content: string;
  createdAt: string;
  author: MomentAuthor;
}

interface Moment {
  id: string;
  author: MomentAuthor;
  content: string;
  imageUrl?: string | null;
  createdAt: string;
  isLikedByMe: boolean;
  _count: {
    likes: number;
  };
  comments?: Comment[]; // 评论列表
}

export default function MomentList() {
  const [moments, setMoments] = useState<Moment[]>([]);
  const [loading, setLoading] = useState(true);
  const [nextCursor, setNextCursor] = useState<string | null>(null);
  const { user } = useAuth();
  const [publishOpen, setPublishOpen] = useState(false);
  const [content, setContent] = useState('');
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [publishing, setPublishing] = useState(false);
  const [likeLoading, setLikeLoading] = useState<string | null>(null);
  const [deleting, setDeleting] = useState<string | null>(null);

  // 评论相关的状态管理
  const [commenting, setCommenting] = useState<string | null>(null);
  const [commentText, setCommentText] = useState('');
  const [expandedComments, setExpandedComments] = useState<Set<string>>(new Set());

  const fileInputRef = useRef<HTMLInputElement>(null);

  const observer = useRef<IntersectionObserver>();
  const lastMomentElementRef = useCallback((node: HTMLLIElement) => {
    if (loading) return;
    if (observer.current) observer.current.disconnect();
    observer.current = new IntersectionObserver(entries => {
      if (entries[0].isIntersecting && nextCursor) {
        fetchMoments(nextCursor);
      }
    });
    if (node) observer.current.observe(node);
  }, [loading, nextCursor]);

  const fetchMoments = useCallback(async (cursor: string | null = null) => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (cursor) params.append('cursor', cursor);
      params.append('limit', '10');

      const res = await get(`/moments?${params.toString()}`);
      const data = res.data;

      if (!data) throw new Error('获取动态失败');
      
      setMoments(prev => cursor ? [...prev, ...data.moments] : data.moments);
      setNextCursor(data.nextCursor);
    } catch {
      toast.error('获取动态失败');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchMoments();
  }, [fetchMoments]);

  const handlePublish = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!content.trim() && !imageFile) return;
    setPublishing(true);

    let imageUrl = null;

    try {
      // 上传图片
      if (imageFile) {
        const formData = new FormData();
        formData.append('file', imageFile);
        const uploadRes = await post('/uploading', formData);
        imageUrl = uploadRes.data.url;
        if (!imageUrl) {
          throw new Error('图片上传失败');
        }
      }

      // 发布
      const body = { content: content.trim(), imageUrl };
      const res = await post('/moments', body);
      if (!res.data) throw new Error('发布失败');

      toast.success('发布成功');
      setPublishOpen(false);
      setContent('');
      setImageFile(null);
      setImagePreview(null);
      setMoments(prev => [res.data, ...prev]);
    } catch (e: any) {
      toast.error(e.message || '发布失败');
    } finally {
      setPublishing(false);
    }
  }

  const handleLike = async (momentId: string, isLiked: boolean) => {
    if (likeLoading) return;
    setLikeLoading(momentId);
    try {
      setMoments(prev => prev.map(m => m.id === momentId ? {
        ...m,
        isLikedByMe: !isLiked,
        _count: { ...m._count, likes: isLiked ? m._count.likes - 1 : m._count.likes + 1 }
      } : m));
      if (isLiked) {
        await del(`/moments/${momentId}/like`);
      } else {
        await post(`/moments/${momentId}/like`, {});
      }
    } catch (error) {
      toast.error('发布失败');
    } finally {
      setLikeLoading(null);
    }
  }

  const handleDeleteMoment = async (momentId: string) => {
    if (!window.confirm('确定要删除这条动态吗？')) return;
    setDeleting(momentId);
    try {
      await del(`/moments/${momentId}`);
      toast.success('已删除');
      setMoments(prev => prev.filter(m => m.id !== momentId));
    } catch (e: any) {
      toast.error('删除失败');
    } finally {
      setDeleting(null);
    }
  }
  
  const toggleComments = async (momentId: string) => {
    const newExpanded = new Set(expandedComments);
    if (newExpanded.has(momentId)) {
      newExpanded.delete(momentId);
    } else {
      newExpanded.add(momentId);
      // 请求评论列表
      const moment = moments.find(m => m.id === momentId);
      if (moment && !moment.comments) {
        try {
          const res = await get(`/moments/${momentId}/comments`);
          setMoments(prev => prev.map(m => m.id === momentId ? { ...m, comments: res.data } : m));
        } catch (e) {
          toast.error("加载评论失败");
        }
      }
    }
    setExpandedComments(newExpanded);
  };

  const handlePublishComment = async (e: React.FormEvent, momentId: string) => {
    e.preventDefault();
    if (!commentText.trim()) return;
    setCommenting(momentId);
    try {
      const res = await post(`/moments/${momentId}/comments`, { content: commentText });
      const newComment = res.data;
      setMoments(prev => prev.map(m => m.id === momentId ? { ...m, comments: [...(m.comments || []), newComment] } : m));
      setCommentText('');
    } catch (e: any) {
      toast.error(e.message || "评论失败");
    } finally {
      setCommenting(null);
    }
  }
  
  const handleImageSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setImageFile(file);
      const reader = new FileReader();
      reader.onloadend = () => {
        setImagePreview(reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const clearImage = () => {
    setImageFile(null);
    setImagePreview(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  }

  return (
    <div className="flex flex-col h-full bg-gray-50 dark:bg-stone-950">
      <header className="flex-shrink-0 flex items-center justify-between px-4 py-3 border-b dark:border-stone-800 bg-white dark:bg-stone-900">
        <h1 className="font-bold text-lg">朋友圈</h1>
        <Button size="sm" variant="outline" className="gap-1" onClick={() => setPublishOpen(true)}>
          <ImageIcon size={16} /> 发布
        </Button>
      </header>

      <main className="flex-1 overflow-auto">
        {moments.length > 0 ? (
          <ul className="space-y-4 p-4">
            {moments.map((m, index) => (
              <li
                ref={index === moments.length - 1 ? lastMomentElementRef : null}
                key={m.id}
                className="bg-white dark:bg-stone-900 rounded-lg p-4 shadow-sm border"
              >
                <div className="flex items-start">
                  <Avatar className="h-10 w-10 flex-shrink-0">
                    <AvatarImage src={m.author.avatar || undefined} alt={m.author.username} />
                    <AvatarFallback>{m.author.username?.charAt(0).toUpperCase()}</AvatarFallback>
                  </Avatar>
                  <div className="ml-4 flex-1">
                    <div className="flex items-center justify-between">
                      <div>
                        <p className="font-semibold text-gray-800 dark:text-gray-200">{m.author.username}</p>
                        <p className="text-xs text-muted-foreground">{formatDistanceToNow(new Date(m.createdAt), { addSuffix: true, locale: zhCN })}</p>
                      </div>
                      {user?.id === m.author.id && (
                        <Button variant="ghost" size="sm" className="text-destructive hover:text-destructive/80" onClick={() => handleDeleteMoment(m.id)} disabled={deleting === m.id}>
                          {deleting === m.id ? <Loader2 className="animate-spin" size={16}/> : '删除'}
                        </Button>
                      )}
                    </div>
                    <p className="mt-3 text-gray-700 dark:text-gray-300 whitespace-pre-line break-words">{m.content}</p>
                    {m.imageUrl && (
                       <img src={m.imageUrl} alt="moment" className="mt-3 max-h-80 w-auto rounded-lg object-cover border" />
                    )}
                    <div className="flex items-center gap-2 mt-3 pt-3 border-t">
                      <Button variant="ghost" size="sm" className={`flex items-center gap-1.5 ${m.isLikedByMe ? 'text-red-500' : 'text-muted-foreground hover:text-foreground'}`} onClick={() => handleLike(m.id, m.isLikedByMe)} disabled={likeLoading === m.id}>
                        <Heart size={16} fill={m.isLikedByMe ? 'currentColor' : 'none'} />
                        <span>{m._count.likes > 0 ? m._count.likes : '赞'}</span>
                      </Button>
                      <Button variant="ghost" size="sm" className="flex items-center gap-1.5 text-muted-foreground hover:text-foreground" onClick={() => toggleComments(m.id)}>
                        <MessageCircle size={16} />
                        <span>{expandedComments.has(m.id) ? '收起' : '评论'}</span>
                      </Button>
                    </div>
                    {/* Comments Section */}
                    {expandedComments.has(m.id) && (
                      <div className="mt-3 space-y-3 pt-3 border-t">
                        {/* Comment List */}
                        {m.comments && m.comments.length > 0 && m.comments.map(c => (
                          <div key={c.id} className="flex items-start text-sm">
                            <Avatar className="h-7 w-7 mr-2 flex-shrink-0">
                              <AvatarImage src={c.author.avatar || undefined} alt={c.author.username} />
                              <AvatarFallback>{c.author.username?.charAt(0).toUpperCase()}</AvatarFallback>
                            </Avatar>
                            <div className="flex-1 bg-muted/50 rounded-lg px-3 py-2">
                              <span className="font-semibold text-sm text-foreground">{c.author.username}</span>
                              <p className="text-sm text-muted-foreground mt-0.5">{c.content}</p>
                            </div>
                          </div>
                        ))}
                         {/* Comment Form */}
                        <form onSubmit={(e) => handlePublishComment(e, m.id)} className="flex items-center gap-2">
                          <Input
                            placeholder="添加评论..."
                            value={commentText}
                            onChange={e => setCommentText(e.target.value)}
                            className="h-8"
                            disabled={commenting === m.id}
                          />
                          <Button type="submit" size="sm" disabled={commenting === m.id || !commentText.trim()}>
                            {commenting === m.id ? <Loader2 className="animate-spin" size={16}/> : <Send size={16} />}
                          </Button>
                        </form>
                      </div>
                    )}
                  </div>
                </div>
              </li>
            ))}
          </ul>
        ) : !loading && (
          <div className="text-center text-gray-400 py-20">
            <p className="text-lg">暂无动态</p>
            <p className="text-sm">快发布第一条动态吧！</p>
          </div>
        )}
        {loading && (
          <div className="flex justify-center items-center py-4">
            <Loader2 className="animate-spin text-gray-400" />
          </div>
        )}
      </main>
      
      {/* 发布朋友圈 Dialog */}
      <Dialog open={publishOpen} onOpenChange={setPublishOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>发布动态</DialogTitle>
          </DialogHeader>
          <form onSubmit={handlePublish} className="space-y-4">
            <textarea
              rows={5}
              placeholder="分享新鲜事..."
              value={content}
              onChange={e => setContent(e.target.value)}
              disabled={publishing}
              className="w-full rounded-lg bg-gray-100 dark:bg-stone-800 border-0 p-3 text-base resize-none focus:ring-2 focus:ring-blue-200 outline-none"
            />
            {/* Image Upload and Preview */}
            <div>
              <input
                type="file"
                ref={fileInputRef}
                className="hidden"
                accept="image/*"
                onChange={handleImageSelect}
                disabled={publishing}
              />
              {!imagePreview ? (
                <Button type="button" variant="outline" onClick={() => fileInputRef.current?.click()} disabled={publishing}>
                  <ImageIcon className="mr-2 h-4 w-4" />
                  选择图片
                </Button>
              ) : (
                <div className="relative mt-2">
                  <img src={imagePreview} alt="Preview" className="max-h-40 rounded-lg" />
                  <Button
                    type="button"
                    variant="destructive"
                    size="sm"
                    className="absolute top-2 right-2 h-7 w-7 p-0"
                    onClick={clearImage}
                    disabled={publishing}
                  >
                    ×
                  </Button>
                </div>
              )}
            </div>

            <DialogFooter>
              <Button type="submit" disabled={publishing || (!content.trim() && !imageFile)}>
                {publishing ? <Loader2 className="animate-spin mr-1" /> : null}
                发布
              </Button>
              <DialogClose asChild><Button type="button" variant="ghost">取消</Button></DialogClose>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
} 